package com.itcast.demoone.kotlin

fun main() {
   // mapOfDemo()
    mutableMapOf()
}

// 1. 不可变
fun mapOfDemo(){
    // 创建不可变映射
    val countryCapitals = mapOf(
        "china" to "北京",
        "japan" to "东京",
        "france" to "巴黎"
    )

    // 访问元素
    println("中国首都是: ${countryCapitals["china"]}") // 输出: Beijing
    println("包含法国吗? ${countryCapitals.containsKey("france")}") // 输出: true

    // 遍历键值对
    println("\n国家首都列表:")
    countryCapitals.forEach { (country, capital) ->
        println("$country → $capital")
    }

    // 尝试修改会报编译错误
     /*countryCapitals["USA"] = "Washington" // 错误!
     countryCapitals.remove("Japan")     */  // 错误!
}

// 2. 可变
fun mutableMapOf(){
// 1. 创建可变映射
    // 库存
    val inventory = mutableMapOf(
        "Apple" to 10,
        "Banana" to 5,
        "Orange" to 8
    )

    println("\n初始库存:")
    inventory.forEach { (item, count) -> println("$item: $count") }

    // 2. 添加新商品
    inventory["Grape"] = 15

    // 3. 修改现有商品数量
    inventory["Apple"] = 20

    // 4. 删除商品
    inventory.remove("Banana")

    println("\n更新后库存:")
    inventory.forEach { (item, count) -> println("$item: $count") }

    // 5. 批量操作
    inventory.putAll(mapOf("Pear" to 7, "Peach" to 9))
    inventory -= "Orange" // 删除Orange，等价于 remove

    println("\n最终库存:")
    inventory.forEach { (item, count) -> println("$item: $count") }
}